package com.xiaoshi.oauth;


import com.google.common.collect.Maps;
import com.xiaoshi.common.MyResUser;
import com.xiaoshi.system.entity.SysUser;
import com.xiaoshi.interfaces.Constants;
import com.xiaoshi.interfaces.ConstantsGrantType;
import com.xiaoshi.interfaces.MyHttpServiceCode;
import com.xiaoshi.system.service.ISysUserService;
import com.xiaoshi.utils.MapUtils;
import com.xiaoshi.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 令牌  增强器
 */
@Component
public class CustomTokenEnhancer implements TokenEnhancer {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (accessToken instanceof DefaultOAuth2AccessToken) {
            String grantType = authentication.getOAuth2Request().getGrantType();

            if (grantType.equals(ConstantsGrantType.CLIENT_CREDENTIALS)) {
                HashMap<String, Object> map = Maps.newHashMap();
                map.put(Constants.myConstans.CODE, MyHttpServiceCode.SC_OK);
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);

            } else {
                // 认证后自定义返回数据
                MyResUser user = (MyResUser) authentication.getPrincipal();
                Map map = MapUtils.cusTokenput(user);
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
                // 修改最后的登入时间
                SysUser suser = sysUserService.getById(user.getUserId());
                suser.setLastLoginTime(TimeUtils.nowDate());
                sysUserService.updateById(suser);

            }


        }

        return accessToken;
    }


}